package com.xiaobai.java_core.socket;

import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;

/**
 * @Author 王天文
 * @Date 2024/12/15 18:02
 * @Description:
 */
@Slf4j
public class SocketClient {
    private static final String SERVER_IP = "127.0.0.1";
    private static final int SERVER_PORT = 15000;
    private static final int timeout = 1800000;

    public static void main(String[] args) {

        Socket socket = null;
        try {
            // 与服务端建立连接
            socket  = new Socket(SERVER_IP, SERVER_PORT);

            // 发送数据
            OutputStream outputStream = socket.getOutputStream();
            outputStream.write("客户端1写入数据".getBytes());
            // 超时时间，单位：毫秒
            socket.setSoTimeout(timeout);
            // 结束写入
            socket.shutdownOutput();

            // 获取响应数据
            InputStream inputStream = socket.getInputStream();
            int len;
            byte[] data = new byte[1024 * 1024];
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            while ((len = inputStream.read(data)) != -1) {
                byteArrayOutputStream.write(data, 0, len);
            }
            log.info("响应数据：{}", new String(byteArrayOutputStream.toByteArray()));
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
